package com.example.homeworkmutualevaluation.Service;

import com.example.homeworkmutualevaluation.Dao.SubmitDao;
import com.example.homeworkmutualevaluation.Dao.TaskDao;
import com.example.homeworkmutualevaluation.DTO.DetailedTask;
import com.example.homeworkmutualevaluation.Entity.Task;
import com.example.homeworkmutualevaluation.Mapper.TaskMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class TaskService {
    @Resource
    private SubmitDao submitDao;
    @Resource
    private TaskDao taskDao;
    @Resource
    private TaskMapper taskMapper;
    private final static int batchSize = 50;
    public void deleteAllByHomeworkid(int homeworkid) {
        taskDao.deleteAllByHomeworkid(homeworkid);
    }
    public void insert(String evaluator, String submitter, int homeworkid) {
        taskDao.insert(evaluator, submitter, homeworkid);
    }
    public int insert(List<Task> list) {
        int total = 0;
        for (int i = 0; i < list.size(); i += batchSize) {
            total += taskMapper.insertBatchByNative(list.subList(i, Integer.min(list.size(),i + batchSize)));
        }
        return total;
    }
    public List<Task> findTasksNeedToDo(String evaluator, int homeworkid) {
        List<Task> tasks = taskDao.findAllNeedToDo(evaluator, homeworkid);
        tasks.forEach(Task::maskSubmitter);
        return tasks;
    }
    public List<DetailedTask> findTasksHasDone(String evaluator, int homeworkid) {
        return taskDao.findAllHasDoneWithDetail(evaluator, homeworkid);
    }
    public Task findById(int id) {
        return taskDao.findById(id);
    }
    public boolean existPendingTask(String evaluator, int homeworkid) {
        return taskDao.countNeedToDo(evaluator, homeworkid) == 0;
    }
    public int requireTask(String evaluator, int homeworkid) {
        List<String> submitters = submitDao.getMostNeededSubmitters(homeworkid);
        if (submitters.isEmpty()) return -1;
        Collections.shuffle(submitters);
        String submitter = submitters.get(0);
        Task task = new Task(evaluator, submitter, homeworkid, Task.OptionalPending);
        taskDao.save(task);
        return task.getId();
    }
}
